package com.huawei.hms.framework.network.restclient.hianalytics;

import android.content.Context;
import android.os.SystemClock;
import android.text.TextUtils;
import com.huawei.hms.framework.common.ExceptionCode;
import com.huawei.hms.framework.common.Logger;
import com.huawei.hms.framework.common.NetworkUtil;
import com.huawei.hms.framework.common.StringUtils;
import com.huawei.hms.framework.common.hianalytics.HianalyticsBaseData;
import com.huawei.hms.framework.common.hianalytics.HianalyticsHelper;
import com.huawei.hms.framework.common.hianalytics.LinkedHashMapPack;
import com.huawei.hms.framework.network.restclient.hianalytics.RCEventListener.Factory;
import com.huawei.hms.framework.network.restclient.hianalytics.RequestFinishedInfo.Metrics;
import com.huawei.hms.framework.network.restclient.hianalytics.RequestFinishedInfo.MetricsTime;
import com.huawei.hms.framework.network.restclient.hwhttp.Request;
import com.huawei.hms.framework.network.restclient.hwhttp.RequestTask;
import com.huawei.hms.framework.network.restclient.hwhttp.Response;
import com.huawei.hms.framework.network.restclient.hwhttp.Submit;
import com.huawei.hms.framework.network.restclient.hwhttp.cronet.CronetRequestTask;
import com.huawei.hms.framework.network.restclient.hwhttp.netdiag.NetDiagManager;
import com.huawei.hms.framework.network.util.ContextUtil;
import com.huawei.hwCloudJs.d.d;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.json.JSONArray;
import org.json.JSONObject;

public class DefaultRCEventListener extends RCEventListener {
    private static final String TAG = "DefaultRCEventListener";
    private long callId;
    private int callStartNetworkType;
    private long callStartTime;
    private int errorCode;
    private Exception exception;
    private boolean isCanceled;
    private boolean isPathReportableClearText;
    private int listenerFinishState;
    private NetDiagManager netDiagManager;
    private long realCallStartTime;
    private long realTotalTime;
    private Map<String, String> recordMap;
    private List<RequestTask> requestTasks;
    private String requestUrl;
    private List<IOException> retryExceptions;
    private int retryTime;
    private long totalTime;
    private String type;

    public static class DefaultFactory implements Factory {
        boolean isPathReportableClearText;
        final AtomicLong nextCallId;
        String type;

        public DefaultFactory(boolean z) {
            this.nextCallId = new AtomicLong(1);
            this.type = HianalyticsData.IF_NAME_HTTP_EXECUTE;
            this.isPathReportableClearText = z;
        }

        public DefaultFactory(String str, boolean z) {
            this.nextCallId = new AtomicLong(1);
            this.isPathReportableClearText = z;
            this.type = str;
        }

        public RCEventListener create(Submit submit) {
            return new DefaultRCEventListener(submit, this.nextCallId.getAndIncrement(), this.type, this.isPathReportableClearText);
        }
    }

    private DefaultRCEventListener(Submit submit, long j, String str, boolean z) {
        this.retryTime = 0;
        this.requestTasks = new ArrayList();
        this.retryExceptions = new ArrayList();
        this.isCanceled = false;
        this.listenerFinishState = 0;
        this.callId = j;
        this.type = str;
        this.isPathReportableClearText = z;
    }

    private void printElapsedTime(String str) {
        Logger.v(TAG, "callId = %d / %s : ElapsedTime = %d", Long.valueOf(this.callId), str, Long.valueOf(System.currentTimeMillis() - this.callStartTime));
    }

    public void callStart() {
        this.callStartTime = System.currentTimeMillis();
        this.realCallStartTime = SystemClock.elapsedRealtime();
        this.callStartNetworkType = NetworkUtil.getNetworkType(ContextUtil.getContext());
        printElapsedTime("callStart");
    }

    public void acquireRequestStart() {
        printElapsedTime("acquireRequestStart");
    }

    public void acquireRequestEnd(Request request) {
        this.requestUrl = request.getUrl().getUrl();
        printElapsedTime("acquireRequestEnd");
        this.recordMap = request.getRecordParamMap();
    }

    public void convertGrsStart(String str) {
        printElapsedTime("convertGrsStart");
    }

    public void convertGrsEnd(String str) {
        this.requestUrl = str;
        printElapsedTime("convertGrsEnd");
    }

    public void retryInterceptorStart(Request request, RequestTask requestTask) {
        this.retryTime++;
        this.requestTasks.add(requestTask);
        printElapsedTime("retryInterceptorStart");
        if (requestTask instanceof CronetRequestTask) {
            addAnnotation((CronetRequestTask) requestTask);
        }
    }

    public void retryInterceptorFailed(IOException iOException) {
        this.retryExceptions.add(iOException);
        printElapsedTime("retryInterceptorFailed");
    }

    public void retryInterceptorEnd(Response response) {
        printElapsedTime("retryInterceptorEnd");
    }

    public void callEnd(Response response) {
        setListenerFinish(2);
        this.totalTime = System.currentTimeMillis() - this.callStartTime;
        this.realTotalTime = SystemClock.elapsedRealtime() - this.realCallStartTime;
        this.errorCode = response.getCode();
        handleReport(Integer.valueOf(response.getCode()));
        printElapsedTime("callEnd");
    }

    public void callFailed(Exception exception) {
        setListenerFinish(2);
        this.totalTime = System.currentTimeMillis() - this.callStartTime;
        this.realTotalTime = SystemClock.elapsedRealtime() - this.realCallStartTime;
        if (this.isCanceled) {
            handleReport(Integer.valueOf(ExceptionCode.CANCEL));
            this.errorCode = ExceptionCode.CANCEL;
        } else {
            handleReport(exception);
            this.exception = exception;
        }
        printElapsedTime("callFailed");
    }

    public void callFinishAtNetLib() {
        Logger.v(TAG, "call finish at net lib, try to report data to AIOps");
        setListenerFinish(1);
        if (this.exception != null) {
            handleReport(this.exception);
        } else {
            handleReport(Integer.valueOf(this.errorCode));
        }
    }

    private synchronized void setListenerFinish(int i) {
        this.listenerFinishState |= i;
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    private synchronized <T> void handleReport(final T r8) {
        /*
        r7 = this;
        r1 = 1;
        r0 = 0;
        monitor-enter(r7);
        r2 = r7.requestTasks;	 Catch:{ all -> 0x004b }
        r2 = r2.size();	 Catch:{ all -> 0x004b }
        if (r2 <= 0) goto L_0x004e;
    L_0x000b:
        r2 = r7.requestTasks;	 Catch:{ all -> 0x004b }
        r3 = r7.requestTasks;	 Catch:{ all -> 0x004b }
        r3 = r3.size();	 Catch:{ all -> 0x004b }
        r3 = r3 + -1;
        r2 = r2.get(r3);	 Catch:{ all -> 0x004b }
        r2 = r2 instanceof com.huawei.hms.framework.network.restclient.hwhttp.cronet.CronetRequestTask;	 Catch:{ all -> 0x004b }
        if (r2 == 0) goto L_0x004e;
    L_0x001d:
        r2 = "DefaultRCEventListener";
        r3 = "listenerFinishState:%d";
        r4 = 1;
        r4 = new java.lang.Object[r4];	 Catch:{ all -> 0x004b }
        r5 = 0;
        r6 = r7.listenerFinishState;	 Catch:{ all -> 0x004b }
        r6 = java.lang.Integer.valueOf(r6);	 Catch:{ all -> 0x004b }
        r4[r5] = r6;	 Catch:{ all -> 0x004b }
        com.huawei.hms.framework.common.Logger.v(r2, r3, r4);	 Catch:{ all -> 0x004b }
        r2 = r7.listenerFinishState;	 Catch:{ all -> 0x004b }
        r2 = r2 & 3;
        r3 = 3;
        if (r2 == r3) goto L_0x004e;
    L_0x0037:
        if (r0 == 0) goto L_0x0049;
    L_0x0039:
        r0 = com.huawei.hms.framework.common.hianalytics.HianalyticsHelper.getInstance();	 Catch:{ all -> 0x004b }
        r0 = r0.getReportExecutor();	 Catch:{ all -> 0x004b }
        r1 = new com.huawei.hms.framework.network.restclient.hianalytics.DefaultRCEventListener$1;	 Catch:{ all -> 0x004b }
        r1.<init>(r8);	 Catch:{ all -> 0x004b }
        r0.execute(r1);	 Catch:{ all -> 0x004b }
    L_0x0049:
        monitor-exit(r7);
        return;
    L_0x004b:
        r0 = move-exception;
        monitor-exit(r7);
        throw r0;
    L_0x004e:
        r0 = r1;
        goto L_0x0037;
        */
        throw new UnsupportedOperationException("Method not decompiled: com.huawei.hms.framework.network.restclient.hianalytics.DefaultRCEventListener.handleReport(java.lang.Object):void");
    }

    public void cancel() {
        this.isCanceled = true;
    }

    public <T> void reportData(T t) {
        if (HianalyticsHelper.getInstance().isEnableReport(ContextUtil.getContext())) {
            long j;
            Context context = ContextUtil.getContext();
            HianalyticsData hianalyticsData = new HianalyticsData();
            this.retryTime--;
            HianalyticsBaseData put = hianalyticsData.put(HianalyticsData.REQ_START, this.callStartTime).put(HianalyticsData.CALL_START_NETWORK_TYPE, (long) this.callStartNetworkType).put(HianalyticsData.IF_NAME, this.type).put(HianalyticsData.NETWORK_TYPE, (long) NetworkUtil.getNetworkType(context)).put(HianalyticsData.TOTAL_TIME, this.realTotalTime);
            String str = HianalyticsData.REQUEST_RETRY;
            if (this.retryTime < 0) {
                j = 0;
            } else {
                j = (long) this.retryTime;
            }
            put.put(str, j);
            if (this.netDiagManager != null) {
                if (this.netDiagManager.getTcpMetrics() == null || this.netDiagManager.getUdpMetrics() == null) {
                    Logger.v(TAG, "netDiagManager query fail");
                } else {
                    hianalyticsData.put(HianalyticsData.ND_TCP_STATUS, (long) this.netDiagManager.getTcpMetrics().getStatusCode()).put(HianalyticsData.ND_TCP_TIME, this.netDiagManager.getTcpMetrics().getTotalTime()).put(HianalyticsData.ND_DNS_STATUS, (long) this.netDiagManager.getUdpMetrics().getStatusCode()).put(HianalyticsData.ND_DNS_TIME, this.netDiagManager.getUdpMetrics().getTotalTime());
                }
            }
            if (this.recordMap != null) {
                for (String str2 : this.recordMap.keySet()) {
                    hianalyticsData.put(str2, (String) this.recordMap.get(str2));
                }
            }
            if (t instanceof Integer) {
                hianalyticsData.put(HianalyticsData.ERROR_CODE, (long) ((Integer) t).intValue());
            }
            try {
                URL url = new URL(this.requestUrl);
                hianalyticsData.put(HianalyticsData.ORIGIN_DOMAIN, url.getHost());
                if (this.isPathReportableClearText) {
                    hianalyticsData.put(HianalyticsData.API_ID, url.getPath());
                } else {
                    hianalyticsData.put(HianalyticsData.API_ID, StringUtils.anonymizeMessage(url.getPath()));
                }
            } catch (MalformedURLException e) {
                Logger.w(TAG, "the url is error,and can't known the host and path!");
                hianalyticsData.put(HianalyticsData.ORIGIN_DOMAIN, d.b);
                hianalyticsData.put(HianalyticsData.API_ID, d.b);
            }
            addNetData(hianalyticsData);
            Logger.v(TAG, hianalyticsData);
            HianalyticsHelper.getInstance().onEvent(hianalyticsData.get());
            return;
        }
        Logger.i(TAG, "HianalyticsHelper report disable");
    }

    private void addNetData(HianalyticsData hianalyticsData) {
        int size = this.requestTasks.size();
        if (size > 0) {
            hianalyticsData.put(createSingleNetData((RequestTask) this.requestTasks.get(size - 1)));
            JSONArray jSONArray = new JSONArray();
            for (int i = 0; i < size - 1; i++) {
                jSONArray.put(new JSONObject(createSingleNetData((RequestTask) this.requestTasks.get(i))));
            }
            if (jSONArray.length() > 0) {
                hianalyticsData.put(HianalyticsData.FAILED_INFO, jSONArray.toString());
            }
        }
    }

    private LinkedHashMap<String, String> createSingleNetData(RequestTask requestTask) {
        Object e;
        String arrays;
        Object successIp;
        long connectRetryTime;
        MetricsTime metricsRealTime;
        Exception exception;
        LinkedHashMapPack linkedHashMapPack = new LinkedHashMapPack();
        if (requestTask != null) {
            RequestFinishedInfo requestFinishedInfo = requestTask.getRequestFinishedInfo();
            if (requestFinishedInfo != null) {
                Metrics metrics = requestFinishedInfo.getMetrics();
                List connectIps = metrics.getConnectIps();
                if (connectIps.isEmpty()) {
                    try {
                        for (InetAddress hostAddress : InetAddress.getAllByName(requestFinishedInfo.getHost())) {
                            connectIps.add(hostAddress.getHostAddress());
                        }
                    } catch (UnknownHostException e2) {
                        e = e2;
                        Logger.w(TAG, e);
                        if (connectIps.isEmpty()) {
                            arrays = Arrays.toString(connectIps.toArray());
                        } else {
                            arrays = null;
                        }
                        successIp = requestFinishedInfo.getMetrics().getSuccessIp();
                        if (!TextUtils.isEmpty(successIp)) {
                            arrays = arrays + "/" + successIp;
                        }
                        connectRetryTime = (long) (metrics.getConnectRetryTime() - 1);
                        linkedHashMapPack.put(HianalyticsData.SERVER_IP, arrays).put(HianalyticsData.DOMAIN, requestFinishedInfo.getHost()).put(HianalyticsData.REQ_SIZE, metrics.getRequestByteCount()).put(HianalyticsData.RSP_SIZE, metrics.getResponseByteCount()).put(HianalyticsData.CONNECT_RETRY, connectRetryTime < 0 ? connectRetryTime : 0).put(HianalyticsData.PROTOCOL, metrics.getProtocol()).put(HianalyticsData.PROTOCOL_IMPL, requestFinishedInfo.getNetworkSdkType());
                        metricsRealTime = requestFinishedInfo.getMetricsRealTime();
                        linkedHashMapPack.put(HianalyticsData.REQ_TOTAL_TIME, metricsRealTime.getTotalTime()).put(HianalyticsData.TCP_CONN_TIME, getIntervalTime(metricsRealTime.getSecureConnectStartTime(), metricsRealTime.getConnectStartTime())).put(HianalyticsData.SSL_TIME, getIntervalTime(metricsRealTime.getSecureConnectEndTime(), metricsRealTime.getSecureConnectStartTime())).put(HianalyticsData.CONNECT_TIME, getIntervalTime(metricsRealTime.getConnectEndTime(), metricsRealTime.getConnectStartTime())).put(HianalyticsData.REQ_START_TRANSFER, getIntervalTime(metricsRealTime.getRequestHeadersStartTime(), metricsRealTime.getCallStartTime())).put(HianalyticsData.TTFB, requestFinishedInfo.getMetricsTime().getTtfb()).put(HianalyticsData.DNS_TIME, getIntervalTime(metricsRealTime.getDnsEndTime(), metricsRealTime.getDnsStartTime())).put(HianalyticsData.DNS_TYPE, metrics.getDnsType()).put(HianalyticsData.DNS_CACHE, (long) metrics.getDnsCache()).put(HianalyticsData.DNS_SERVER_IPS, NetworkUtil.getDnsServerIps(ContextUtil.getContext())).put(HianalyticsData.REQ_START_TIME, requestFinishedInfo.getMetricsTime().getCallStartTime());
                        exception = requestFinishedInfo.getException();
                        if (exception == null) {
                            linkedHashMapPack.put(HianalyticsData.ERROR_CODE, (long) ExceptionCode.getErrorCodeFromException(exception)).put(HianalyticsData.EXCEPTION_NAME, exception.getClass().getSimpleName()).put(HianalyticsData.EXCEPTION_MESSAGE, StringUtils.anonymizeMessage(exception.getMessage()));
                        } else if (requestFinishedInfo.getResponse() != null) {
                            arrays = getDlFrom(requestFinishedInfo.getResponse());
                            if (!TextUtils.isEmpty(arrays)) {
                                linkedHashMapPack.put(HianalyticsData.DL_FROM, arrays);
                            }
                        }
                        return linkedHashMapPack.getAll();
                    } catch (NullPointerException e3) {
                        e = e3;
                        Logger.w(TAG, e);
                        if (connectIps.isEmpty()) {
                            arrays = null;
                        } else {
                            arrays = Arrays.toString(connectIps.toArray());
                        }
                        successIp = requestFinishedInfo.getMetrics().getSuccessIp();
                        if (TextUtils.isEmpty(successIp)) {
                            arrays = arrays + "/" + successIp;
                        }
                        connectRetryTime = (long) (metrics.getConnectRetryTime() - 1);
                        if (connectRetryTime < 0) {
                        }
                        linkedHashMapPack.put(HianalyticsData.SERVER_IP, arrays).put(HianalyticsData.DOMAIN, requestFinishedInfo.getHost()).put(HianalyticsData.REQ_SIZE, metrics.getRequestByteCount()).put(HianalyticsData.RSP_SIZE, metrics.getResponseByteCount()).put(HianalyticsData.CONNECT_RETRY, connectRetryTime < 0 ? connectRetryTime : 0).put(HianalyticsData.PROTOCOL, metrics.getProtocol()).put(HianalyticsData.PROTOCOL_IMPL, requestFinishedInfo.getNetworkSdkType());
                        metricsRealTime = requestFinishedInfo.getMetricsRealTime();
                        linkedHashMapPack.put(HianalyticsData.REQ_TOTAL_TIME, metricsRealTime.getTotalTime()).put(HianalyticsData.TCP_CONN_TIME, getIntervalTime(metricsRealTime.getSecureConnectStartTime(), metricsRealTime.getConnectStartTime())).put(HianalyticsData.SSL_TIME, getIntervalTime(metricsRealTime.getSecureConnectEndTime(), metricsRealTime.getSecureConnectStartTime())).put(HianalyticsData.CONNECT_TIME, getIntervalTime(metricsRealTime.getConnectEndTime(), metricsRealTime.getConnectStartTime())).put(HianalyticsData.REQ_START_TRANSFER, getIntervalTime(metricsRealTime.getRequestHeadersStartTime(), metricsRealTime.getCallStartTime())).put(HianalyticsData.TTFB, requestFinishedInfo.getMetricsTime().getTtfb()).put(HianalyticsData.DNS_TIME, getIntervalTime(metricsRealTime.getDnsEndTime(), metricsRealTime.getDnsStartTime())).put(HianalyticsData.DNS_TYPE, metrics.getDnsType()).put(HianalyticsData.DNS_CACHE, (long) metrics.getDnsCache()).put(HianalyticsData.DNS_SERVER_IPS, NetworkUtil.getDnsServerIps(ContextUtil.getContext())).put(HianalyticsData.REQ_START_TIME, requestFinishedInfo.getMetricsTime().getCallStartTime());
                        exception = requestFinishedInfo.getException();
                        if (exception == null) {
                            linkedHashMapPack.put(HianalyticsData.ERROR_CODE, (long) ExceptionCode.getErrorCodeFromException(exception)).put(HianalyticsData.EXCEPTION_NAME, exception.getClass().getSimpleName()).put(HianalyticsData.EXCEPTION_MESSAGE, StringUtils.anonymizeMessage(exception.getMessage()));
                        } else if (requestFinishedInfo.getResponse() != null) {
                            arrays = getDlFrom(requestFinishedInfo.getResponse());
                            if (TextUtils.isEmpty(arrays)) {
                                linkedHashMapPack.put(HianalyticsData.DL_FROM, arrays);
                            }
                        }
                        return linkedHashMapPack.getAll();
                    }
                }
                if (connectIps.isEmpty()) {
                    arrays = null;
                } else {
                    arrays = Arrays.toString(connectIps.toArray());
                }
                successIp = requestFinishedInfo.getMetrics().getSuccessIp();
                if (TextUtils.isEmpty(successIp)) {
                    arrays = arrays + "/" + successIp;
                }
                connectRetryTime = (long) (metrics.getConnectRetryTime() - 1);
                if (connectRetryTime < 0) {
                }
                linkedHashMapPack.put(HianalyticsData.SERVER_IP, arrays).put(HianalyticsData.DOMAIN, requestFinishedInfo.getHost()).put(HianalyticsData.REQ_SIZE, metrics.getRequestByteCount()).put(HianalyticsData.RSP_SIZE, metrics.getResponseByteCount()).put(HianalyticsData.CONNECT_RETRY, connectRetryTime < 0 ? connectRetryTime : 0).put(HianalyticsData.PROTOCOL, metrics.getProtocol()).put(HianalyticsData.PROTOCOL_IMPL, requestFinishedInfo.getNetworkSdkType());
                metricsRealTime = requestFinishedInfo.getMetricsRealTime();
                linkedHashMapPack.put(HianalyticsData.REQ_TOTAL_TIME, metricsRealTime.getTotalTime()).put(HianalyticsData.TCP_CONN_TIME, getIntervalTime(metricsRealTime.getSecureConnectStartTime(), metricsRealTime.getConnectStartTime())).put(HianalyticsData.SSL_TIME, getIntervalTime(metricsRealTime.getSecureConnectEndTime(), metricsRealTime.getSecureConnectStartTime())).put(HianalyticsData.CONNECT_TIME, getIntervalTime(metricsRealTime.getConnectEndTime(), metricsRealTime.getConnectStartTime())).put(HianalyticsData.REQ_START_TRANSFER, getIntervalTime(metricsRealTime.getRequestHeadersStartTime(), metricsRealTime.getCallStartTime())).put(HianalyticsData.TTFB, requestFinishedInfo.getMetricsTime().getTtfb()).put(HianalyticsData.DNS_TIME, getIntervalTime(metricsRealTime.getDnsEndTime(), metricsRealTime.getDnsStartTime())).put(HianalyticsData.DNS_TYPE, metrics.getDnsType()).put(HianalyticsData.DNS_CACHE, (long) metrics.getDnsCache()).put(HianalyticsData.DNS_SERVER_IPS, NetworkUtil.getDnsServerIps(ContextUtil.getContext())).put(HianalyticsData.REQ_START_TIME, requestFinishedInfo.getMetricsTime().getCallStartTime());
                exception = requestFinishedInfo.getException();
                if (exception == null) {
                    linkedHashMapPack.put(HianalyticsData.ERROR_CODE, (long) ExceptionCode.getErrorCodeFromException(exception)).put(HianalyticsData.EXCEPTION_NAME, exception.getClass().getSimpleName()).put(HianalyticsData.EXCEPTION_MESSAGE, StringUtils.anonymizeMessage(exception.getMessage()));
                } else if (requestFinishedInfo.getResponse() != null) {
                    arrays = getDlFrom(requestFinishedInfo.getResponse());
                    if (TextUtils.isEmpty(arrays)) {
                        linkedHashMapPack.put(HianalyticsData.DL_FROM, arrays);
                    }
                }
                return linkedHashMapPack.getAll();
            }
        }
        Logger.w(TAG, "the task or reqInfo is null,and the collection is failed!");
        return linkedHashMapPack.getAll();
    }

    private String getDlFrom(Response response) {
        String str = response.getHeaders().get("dl-from");
        for (String str2 : HianalyticsData.DL_WHITESPACE) {
            if (str2.equalsIgnoreCase(str)) {
                return str2;
            }
        }
        return "";
    }

    private long getIntervalTime(long j, long j2) {
        if (j2 == 0 || j == 0) {
            return 0;
        }
        return j - j2;
    }

    private void addAnnotation(CronetRequestTask cronetRequestTask) {
        cronetRequestTask.setRcEventListener(this);
    }

    public void setNetDiagManager(NetDiagManager netDiagManager) {
        this.netDiagManager = netDiagManager;
    }
}
